<template>
  <el-dialog :close-on-click-modal="false" :visible.sync="dialog" :title="isAdd ? '新增角色' : '编辑角色'" append-to-body width="600px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="角色名称" prop="role">
        <el-input v-model="form.role" style="width: 370px;" :disabled="!isAdd"/>
      </el-form-item>
      <el-form-item label="描述信息">
        <el-input v-model="form.roleName" style="width: 370px;" rows="5" type="textarea"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="confirm">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { role_add, role_update } from '@/api/system';
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      dialog: false,
      form: {
        uuid: null,
        role: '',
        roleName: ''
      },
      rules: {
        role: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      }
    };
  },
  methods: {
    cancel() {
      this.resetForm();
    },
    confirm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.isAdd) {
            this.doAdd(this.form);
          } else this.doEdit(this.form);
        } else {
          return false;
        }
      });
    },
    async doAdd(form) {
      try {
        await role_add(form);
        this.loading = false;
        this.$message({
          type: 'success',
          message: '添加成功'
        });
        this.$parent.getRoles(0);
        this.resetForm();
      } catch (error) {
        this.loading = false;
      }
    },
    async doEdit(form) {
      try {
        await role_update(form);
        this.$message({
          type: 'success',
          message: '修改成功'
        });
        this.loading = false;
        this.$parent.getRoles(0);
        this.resetForm();
      } catch (error) {
        this.loading = false;
      }
    },
    resetForm() {
      this.dialog = false;
      this.$refs['form'].resetFields();
      this.form = {
        uuid: null,
        role: '',
        roleName: ''
      };
    },

    restoreForm() {
      this.form = {
        uuid: null,
        role: '',
        roleName: ''
      };
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
/deep/ .el-input-number .el-input__inner {
  text-align: left;
}
</style>
